import common from './common.js'
import db from './db.js'
import sock from './socket.js'
import apis from './apis.js'

export default {
	login: async (data) => {
	    common.userName = data.UserName;
		common.token(data.Password); //设置token
		common.loginUser = data;
		await db.createTables();
		await sock.initSocket(); //初始化websocket
		data = await Promise.all([apis.getGroups(), apis.getFriends(), db.getNewestChatMessage()]); //获取群组、好友数据和最新聊天消息
		let groups = data[0].Result;
		let friends = data[1].Result;
		let msgs = data[2];
		let minId = await db.getMinId();
		common.minId(Math.min(0, minId));
		common.friends(friends);
		groups.forEach(group => {
			common.mappingGroupMembers(group.Item2); //映射群组成员
		});
		common.groups(
			groups.map(c => {
				c.Item1.members = c.Item2;
				return c.Item1;
			})
		);
		let newMsgs = [];
		let avatars = common.friends().map(f => f.Avatar);
		avatars.push(common.loginUser.Avatar);
		await apis.BatchCheckDownloadAvatars(avatars); //批量下载头像
		msgs.forEach(msg => {
			let newMsg = common.createNewMessage(msg);
			if (newMsg) {
				newMsgs.push(newMsg);
			} else {
				db.deleteMessageByOther(msg);
			}
		});
		common.newMessage = newMsgs;
		common.connected = true;
		//登录
		uni.reLaunch({
			url: '/pages/message/list'
		});
	}
}
